#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置操作模块
处理FreeNote应用的配置文件管理
"""

import configparser
import os
from pathlib import Path


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file="freenote.ini"):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self._load_config()
    
    def _get_default_config(self):
        """获取默认配置"""
        return {
            'settings': {
                'folder': './notes/',
                'filename': '<MM><DD>_<hh><mm><ss>',
                'ext': '.txt'
            }
        }
    
    def _load_config(self):
        """加载配置文件"""
        default_config = self._get_default_config()
        
        if os.path.exists(self.config_file):
            self.config.read(self.config_file, encoding='utf-8')
        else:
            # 创建默认配置文件
            for section, options in default_config.items():
                self.config.add_section(section)
                for key, value in options.items():
                    self.config.set(section, key, value)
            self.save_config()
        
        # 确保保存目录存在
        save_dir = self.get_setting('folder')
        if save_dir:
            Path(save_dir).mkdir(parents=True, exist_ok=True)
    
    def save_config(self):
        """保存配置文件"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            self.config.write(f)
    
    def get_setting(self, key, fallback=''):
        """获取配置项"""
        return self.config.get('settings', key, fallback=fallback)
    
    def set_setting(self, key, value):
        """设置配置项"""
        self.config.set('settings', key, value)
        self.save_config()
    
    def get_all_settings(self):
        """获取所有配置项"""
        return dict(self.config.items('settings'))


# 全局配置管理器实例
_config_manager = None

def get_config_manager():
    """获取配置管理器实例（单例模式）"""
    global _config_manager
    if _config_manager is None:
        _config_manager = ConfigManager()
    return _config_manager

def get_setting(key, fallback=''):
    """获取配置项的便捷函数"""
    return get_config_manager().get_setting(key, fallback)

def set_setting(key, value):
    """设置配置项的便捷函数"""
    get_config_manager().set_setting(key, value)